package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 预编译SQL，防止SQL注入攻击
 * 1.先将SQL语句发送给数据库，让数据库生成执行计划理解SQL执行意图(?占位)
 * 2.创建预编译SQL语句执行对象(prepareStatement)
 * 3.设置SQL语句中的?的值,并执行SQL语句(setString(index,value))
 */
public class JDBCDemo8 {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection();){
            // 接收用户输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("登录功能");
            System.out.println("请输入用户名:");
            String username = scanner.nextLine();
            System.out.println("请输入密码:");
            String password = scanner.nextLine();
            // 执行预编译SQL
            String sql = "SELECT id,username,password,nickname FROM userinfo " +
                    "WHERE username=? AND password=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            /*
                设置 ? 对应的值
                ? 是整型,ps.setInt(...)
                ? 是字符串,ps.setString(...)
             */
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet resultSet = ps.executeQuery();
            // 判断结果
            if (resultSet.next()){
                String nickname = resultSet.getString("nickname");
                System.out.println("登录成功,欢迎:" + nickname);
            }else{
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
